package io.web.bi.converter;

import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * Converters.
 *
 * @date 2023-07-24
 */
public class Converters {

    private final Map<Class<?>, Converter<?>> converters = new HashMap<>();

    public Converters() {
        loadConverters();
    }

    private static class ConvertersHolder {
        private static final Converters INSTANCE = new Converters();
    }

    public static Converters getInstance() {
        return ConvertersHolder.INSTANCE;
    }

    public void addConverters(Converter<?> converter) {
        Class<?> type = resolveConverterType(converter);
        converters.put(type, converter);
    }

    public Converter<?> findConverter(Class<?> classt) {
        return converters.get(classt);
    }

    private Class<?> resolveConverterType(Converter<?> converter) {
        Type genericSuperclass = converter.getClass().getGenericSuperclass();
        return (Class<?>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
    }

    public void loadConverters() {
        for (Converter<?> converter : ServiceLoader.load(Converter.class)) {
            addConverters(converter);
        }
    }
}
